package com.sgb.goods.utils.base.adapter;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * RecycleView公用适配器 结合dataBinding
 * @author cyj
 * @param <T>
 */
public class BaseCommonAdapter<T> extends BaseQuickAdapter<T, BaseViewHolder> {

    public BaseCommonAdapter baseCommonAdapter = BaseCommonAdapter.this;

    /**
     * 实体类中绑定的 variable 中的 name
     */
    private int variableId = 0;

    /**
     * BaseCommonAdapter 构造
     */
    public BaseCommonAdapter(int layoutResId) {
        this(layoutResId, null, 0);
    }

    /**
     * BaseCommonAdapter 构造
     */
    public BaseCommonAdapter(int layoutResId, int variableId) {
        this(layoutResId, null, variableId);
    }

    /**
     * BaseCommonAdapter 构造器
     * @param layoutResId
     * @param list
     * @param variableId
     */
    public BaseCommonAdapter(int layoutResId, List<T> list, int variableId) {
        super(layoutResId, list);
        this.variableId = variableId;
    }

    protected void convert(BaseViewHolder baseHolder, ViewDataBinding dataBinding, T entity) {}

    @Override
    final protected void convert(@NotNull BaseViewHolder baseHolder, T entity) {
        ViewDataBinding dataBinding = DataBindingUtil.bind(baseHolder.itemView);
        if(null != dataBinding) {
            if(this.variableId > 0) {
                dataBinding.setVariable(this.variableId, entity);
            }
            //防止数据闪烁
            dataBinding.executePendingBindings();
        }
        convert(baseHolder, dataBinding, entity);
    }

}
